/**
 * 管理员角色下拉
 */

import { Select, SelectProps } from 'antd';
import { useImperativeHandle, useState } from 'react';

import { IRoleRestFillRefHandler } from '../../types';
import { useGetSysRoleLiestAll } from '../../service/sys-role-service';

interface IRoleSelectProps extends SelectProps<number> {
  handleChange: (value: number) => void;
  onRef?: React.MutableRefObject<IRoleRestFillRefHandler | undefined>;
}

export const RolePermissionSelect = ({ handleChange, onRef }: IRoleSelectProps) => {
  const { isLoading, isError, data: dataSource } = useGetSysRoleLiestAll();
  const [val, setVal] = useState<number>();
  const onChange = (value: number) => {
    setVal(value);
    handleChange(value);
  };

  /**向外暴露的重置方法 */
  useImperativeHandle(onRef, () => ({
    rest: () => {
      setVal(undefined);
    },
    fill: (sysRoleId) => {
      setVal(sysRoleId);
    },
  }));
  
  return (
    <Select placeholder={'角色选择树'} value={val} onChange={onChange} loading={isLoading}>
      {isError
        ? null
        : dataSource?.map((data) => {
          return (
            data.sysRoleId === 0 ? null : <Select.Option key={data.sysRoleId} value={data.sysRoleId}>
              {data.sysRoleName}
            </Select.Option>
          );
        })}
    </Select >
  );
};
